package com.roncoo.education.api;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageInfo;
import com.roncoo.education.api.request.MyCollectionRequest;
import com.roncoo.education.api.request.PageBaseRequest;
import com.roncoo.education.db.entity.MyCollection;
import com.roncoo.education.db.entity.MyHistory;
import com.roncoo.education.db.service.MyCollectionService;
import com.roncoo.education.db.service.MyHistoryService;
import com.roncoo.education.util.MyJwtUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class MyCollectionController {

    @Resource
    private MyCollectionService myCollectionService;
    @Resource
    private MyHistoryService myHistoryService;

    @Resource
    private MyJwtUtil myJwtUtil;

    @PostMapping("/saveMyCollection")
    public String saveMyCollection(@Valid @RequestBody MyCollectionRequest req, HttpServletRequest request){
        String token = request.getHeader("token");
        if(StrUtil.isNotBlank(token)) {
            Long userId = myJwtUtil.getUsernameFromToken(token);
            Map<String, String> ret = myCollectionService.saveCollection(userId, req.getProductId(), req.getProductType());
            return JSONUtil.toJsonStr(ret);
        }
        return "";
    }

    @PostMapping("/delMyCollection")
    public String deleteCollection(Long id,HttpServletRequest request){
        String token = request.getHeader("token");
        Long userId = myJwtUtil.getUsernameFromToken(token);
        if(userId!=null){
            myCollectionService.deleteCollection(id);
            return "success";
        }
        return "";
    }





    @PostMapping("/getCollectionPages")
    public String getCollectionPages(@Valid @RequestBody PageBaseRequest req, HttpServletRequest request){
        String token = request.getHeader("token");
        Long userId = myJwtUtil.getUsernameFromToken(token);
        PageInfo<MyCollection> pageInfo = myCollectionService.getPages(userId,req);
        return JSONUtil.toJsonStr(pageInfo);
    }

    @PostMapping("/getHistoryPages")
    public String getHistoryPages(@Valid @RequestBody PageBaseRequest req, HttpServletRequest request){
        String token = request.getHeader("token");
        Long userId = myJwtUtil.getUsernameFromToken(token);
        PageInfo<MyHistory> pageInfo = myHistoryService.getHistoryPages(userId,req);
        return JSONUtil.toJsonStr(pageInfo);
    }
}
